import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export function getUser (): RootThunkAction {
  return async (dispatch) => {
    // 1. 发请求
    const res = await request.get<ApiResponse<User>>('/user')
    console.log('getUser...', res.data.data)
    // 2. 保存信息
    dispatch({
      type: 'profile/getUser',
      payload: res.data.data
    })
  }
}

export function getUserProfile (): RootThunkAction {
  return async (dispatch) => {
    // 1. 发请求
    const res = await request.get<ApiResponse<UserProfile>>('/user/profile')
    console.log('getUserProfile...', res.data.data)
    // 2. 保存信息
    dispatch({
      type: 'profile/getUserProfile',
      payload: res.data.data
    })
  }
}

export function updateUserProfile (
  type: string,
  value: string
): RootThunkAction {
  return async (dispatch) => {
    // 1. 发请求<ApiResponse<UserProfile>>
    const res = await request.patch('/user/profile', {
      [type]: value
    })
    console.log('updateUserProfile...', res.data)
    // 2. 重发请求
    dispatch(getUserProfile())
  }
}
